package com.my.ads.lib.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.my.ads.lib.AdSummary;
import com.my.ads.lib.Config;
import com.my.ads.lib.bean.DataBean;
import com.my.ads.lib.listen.LockScreenReceiver;
import com.my.ads.lib.utils.Utils;
import com.my.ads.lib.view.BottomToTopFinishLayout;
import com.rapid.clean.deep.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * Created by xuanyang on 2018/3/6.
 */

public class LockScreenActivity extends BaseActivity{


    /**
     * virbate means that the screen is unlocked success
     */
    private void virbate() {
        Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }
    private TextView my_time, my_date, my_week, text_charging;
    private ImageView img_lock_gift, img_menu;

    private LockScreenReceiver myBroadcastReceiver;
    private IntentFilter intentFilter;
    public static boolean isLocked = false;
    private RelativeLayout container;
    private PopupWindow pw;
    private LayoutInflater inflater;

    private boolean isOpen = false;




    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        setContentView(R.layout.lock_screen);
        initViews();
        //订阅
        EventBus.getDefault().register(this);

        img_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.menu_layout, null);
                TextView textView = (TextView) view.findViewById(R.id.text_off);
                pw = new PopupWindow(view, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                pw.setFocusable(true);
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish();
                    }
                });
                pw.showAsDropDown(img_menu);
            }
        });
        registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));


        //注册广播
        myBroadcastReceiver = new LockScreenReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_TIME_TICK);
        intentFilter.addAction(Intent.ACTION_DATE_CHANGED);
        intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(myBroadcastReceiver, intentFilter);

        isLocked = true;
        BottomToTopFinishLayout bottomFinishLayout = (BottomToTopFinishLayout) findViewById(R.id.huadong);
        bottomFinishLayout.setOnFinishListener(new BottomToTopFinishLayout.OnFinishListener() {
            @Override
            public void onFinish() {
                if (!isOpen) {
                    virbate();
                    isLocked = false;
                    Random random1 = new Random();
                    if ((random1.nextInt(100) + 1) <= Integer.valueOf(Config.boost_rate)) {
//            Intent intent = new Intent(ActivityScreen.this, OutBooster.class);
//            startActivity(intent);
                        finish();
                    }else {
                        Intent startMain = new Intent(Intent.ACTION_MAIN);
                        startMain.addCategory(Intent.CATEGORY_HOME);
                        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(startMain);
                        finish();
                    }
                    isOpen = true;
                }
            }
        });
        img_lock_gift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent asd=new Intent(LockScreenActivity.this, GiftActivity.class);
                startActivity(asd);
            }
        });
        try {
            if (Integer.valueOf(Utils.getVersionCode(this))< Integer.valueOf(Config.current_version_code)){
                AdSummary.getInstance().showNativeAd(this, container, true);
            }else {
                if("1".equals(Config.is_show_lock_ad)){
                    AdSummary.getInstance().showNativeAd(this, container, true);
                }
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        my_time.setText(getSystemTime());
        my_date.setText(getSystemDate());
        my_week.setText(getSystemWeek());

        long l = Utils.getAvailMemory(this);
        long y = Utils.getTotalMemory(this);
        final double x = (((y - l) / (double) y) * 100);

        try {
            if (Integer.valueOf(Utils.getVersionCode(this))< Integer.valueOf(Config.current_version_code)){
                AdSummary.getInstance().showNativeAd(this, container, true);
            }else {
                if("1".equals(Config.is_show_lock_ad)){
                    AdSummary.getInstance().showNativeAd(this, container, true);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private void initViews() {
        img_menu = (ImageView) findViewById(R.id.img_menu);
        my_time = (TextView) findViewById(R.id.tv_times);
        my_date = (TextView) findViewById(R.id.tv_year_times);
        my_week = (TextView) findViewById(R.id.weeks);
        text_charging = (TextView) findViewById(R.id.text_charging);

        container = (RelativeLayout) findViewById(R.id.root_1);
        img_lock_gift = (ImageView) findViewById(R.id.img_lock_gift);

    }

    //获取电池温度
    private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            /*
             * 如果捕捉到的action是ACTION_BATTERY_CHANGED，就运行onBatteryInfoReceiver()
             */
            if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                // 这个到底是做什么的呢？
            }

        }
    };

    private String getSystemTime() {
        long time = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("HH:mm");
        Date d1 = new Date(time);
        String t1 = format.format(d1);
        return t1;
    }

    private String getSystemDate() {
        long time = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Date d1 = new Date(time);
        String t1 = format.format(d1);
        return t1;
    }

    private String getSystemWeek() {
        Calendar c = Calendar.getInstance();
        String mWay = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
        if ("1".equals(mWay)) {
            mWay = "Sun";
        } else if ("2".equals(mWay)) {
            mWay = "Mon";
        } else if ("3".equals(mWay)) {
            mWay = "Tue";
        } else if ("4".equals(mWay)) {
            mWay = "Wed";
        } else if ("5".equals(mWay)) {
            mWay = "Thu";
        } else if ("6".equals(mWay)) {
            mWay = "Fri";
        } else if ("7".equals(mWay)) {
            mWay = "Sat";
        }
        return mWay;
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void mEvent(DataBean event) {
        if (!TextUtils.isEmpty(event.getMsg())) {
            switch (event.getMsg()) {
                case Config.EventTime:
                    my_time.setText(getSystemTime());
                    break;
                case Config.EventDate:
                    my_date.setText(getSystemDate());
                    my_week.setText(getSystemWeek());
                    break;
                case Config.EventPower:


                    int status = event.getStatus();
                    switch (status) {
                        case BatteryManager.BATTERY_STATUS_CHARGING:
                            text_charging.setVisibility(View.VISIBLE);
                            text_charging.setText(getResources().getText(R.string.charging));
                            break;
                        case BatteryManager.BATTERY_STATUS_FULL:
                            text_charging.setVisibility(View.VISIBLE);
                            text_charging.setText(getResources().getText(R.string.already_full));
                            break;
                        case BatteryManager.BATTERY_STATUS_DISCHARGING:
                        case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
                        default:
                            text_charging.setText(getResources().getText(R.string.uncharged));
                            break;
                    }
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //取消订阅
        EventBus.getDefault().unregister(this);
        unregisterReceiver(myBroadcastReceiver);
        unregisterReceiver(mBatInfoReceiver);
    }




}
